#include "my_uart.h"

uint8_t uart_init_flags = 0;

static const char *TAG = "my_uart";

int my_uart_init(hl_uart_config_t uart_init_params)
{
	 esp_err_t err=ESP_FAIL;
	/* Configure parameters of an UART driver,
	 * communication pins and install the driver */
	uart_config_t uart_config = {
		.baud_rate = uart_init_params.bate,
		.data_bits = UART_DATA_8_BITS,
		.parity = UART_PARITY_DISABLE,
		.stop_bits = UART_STOP_BITS_1,
		.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
	};

	if(uart_init_flags & (1<<uart_init_params.uart_num))
	{
		ESP_LOGE(TAG,"Serial port %d has been initialized, please do not initialize again",uart_init_params.uart_num);
		return ESP_FAIL;
	}
	err = uart_param_config(uart_init_params.uart_num, &uart_config);
	if(err!=ESP_OK)
	{
		ESP_LOGE(TAG,"uart[%d] config err:%d",uart_init_params.uart_num,err);
		return ESP_FAIL;
	}            
	err = uart_driver_install(uart_init_params.uart_num, BUF_SIZE * 2, 0, 0,NULL, 0);
	if(err!=ESP_OK)
	{
		ESP_LOGE(TAG,"uart[%d] install err:%d",uart_init_params.uart_num,err);
		return ESP_FAIL;
	}
	uart_init_flags |= (1<<uart_init_params.uart_num);
	return ESP_OK;
}

int my_uart_send_data(uart_port_t uart_num,uint8_t *data,size_t len)
{
	if(uart_init_flags & (1<<uart_num))
	{
		int state=uart_write_bytes(uart_num, (const char *)data, len);
		if(state<0)
		{
			ESP_LOGE(TAG, "uart_num %d write error",uart_num);
			return ESP_FAIL;
		}
	}
	else
	{
		ESP_LOGE(TAG, "uart_num %d need to initial",uart_num);
		return ESP_FAIL;
	}
	return ESP_OK;
}


int my_uart_recv_data(uart_port_t uart_num,uint8_t *data,int *len)
{
	if(uart_init_flags & (1<<uart_num))
	{
		*len = uart_read_bytes(uart_num, data, BUF_SIZE, 20 / portTICK_RATE_MS);
		if(*len == -1)
		{
			ESP_LOGE(TAG, "uart_num %d recv error",uart_num);
			return ESP_FAIL;
		}
	}
	else
	{
		ESP_LOGE(TAG, "uart_num %d need to initial",uart_num);
		return ESP_FAIL;
	}
	return ESP_OK;
}

int my_uart_deinit(uart_port_t uart_num)
{
	ESP_LOGI(TAG,"uart_driver_delete UART_NUM_%d",uart_num);
	if(uart_init_flags & (1<<uart_num))
	{
		ESP_LOGI(TAG,"wait relase uart_recv_flags");
		uart_init_flags &= ~(1 << uart_num);
		vTaskDelay(40 / portTICK_RATE_MS);  //等待接收API退出
		esp_err_t ret = uart_driver_delete(uart_num);
		if(ret != ESP_OK)
		{
			uart_init_flags |= (1<<uart_num);
			ESP_LOGE(TAG,"uart_driver_delete err");
			return ESP_FAIL;
		}
		ESP_LOGI(TAG,"uart_driver_delete OK");
	}
	else
	{
		ESP_LOGE(TAG,"Serial port is not initialized");
		return ESP_FAIL;
	}
	return ESP_OK;
}

